package com.gitee.ixtf.vertx.internal.converter

import cn.hutool.core.convert.ConverterRegistry
import com.gitee.ixtf.vertx.ParameterConverter
import com.gitee.ixtf.vertx.internal.rc
import com.sun.security.auth.UserPrincipal
import graphql.schema.DataFetchingEnvironment
import io.vertx.ext.web.RoutingContext
import io.vertx.ext.web.handler.graphql.ws.Message
import java.security.Principal

object PrincipalParameterConverter : ParameterConverter<Principal> {
  private val converter by lazy { ConverterRegistry.getInstance() }

  override suspend fun convert(env: DataFetchingEnvironment): Principal =
      env.graphQlContext.get<Principal?>(Principal::class.java)
          ?: env.graphQlContext.get<Message?>(Message::class.java)?.let {
            converter.convert(Principal::class.java, it.connectionParams())
          }
          ?: convert(env.rc())

  override suspend fun convert(rc: RoutingContext): Principal =
      converter.convert(Principal::class.java, rc)

  override suspend fun convert(message: io.vertx.core.eventbus.Message<*>): Principal =
      UserPrincipal(message.headers()[Principal::class.java.name])
}
